package app.utils.wechat;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.scyf.bean.GlobalAccessToken;
import com.scyf.weixintool.WeiXinGlobalToken;

public class WeChatJSAPITools {
	
	
	public static JsApiTicket WeChatJSAPI(String  appId,String  appSecret,HttpServletRequest request,HttpSession session) throws Exception{
		String ticket="";
		String nonceStr=UUID.randomUUID().toString();
		long time=System.currentTimeMillis()/1000;
		String baseUrl=request.getRequestURL().toString();
		//获取访问连接中的参数
		Map<String, String[]> params = request.getParameterMap();
		boolean flag=true;
		for(Map.Entry<String, String[]> entry:params.entrySet()) {
			if (flag) {
				baseUrl+=("?"+entry.getKey()+"="+(entry.getValue()!=null&&entry.getValue().length>0?entry.getValue()[0]:""));
				flag=false;
				continue;
			}
			baseUrl+=("&"+entry.getKey()+"="+(entry.getValue()!=null&&entry.getValue().length>0?entry.getValue()[0]:""));
		}
		int expires_in=7200;
		JsApiTicket jsTicket = (JsApiTicket) session.getAttribute("jsTicket");
		if (jsTicket==null || jsTicket.isUpto() || jsTicket.isUrlChang(baseUrl)) {
			//https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi
			GlobalAccessToken globalAccessToken = WeiXinGlobalToken.getGlobalAccessToken(appId, appSecret);
			String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="
					+ globalAccessToken.getAccess_token() + "&type=jsapi";
			URL urlJs = new URL(url);
			HttpURLConnection connection = (HttpURLConnection) urlJs.openConnection();
			connection.setRequestMethod("GET");
			InputStream inputStream = connection.getInputStream();
			StringBuilder builder = new StringBuilder();
			int len = 0;
			byte[] buff = new byte[20];
			while ((len = inputStream.read(buff)) > 0) {
				builder.append(new String(buff, 0, len, "UTF-8"));
			}
			JsonObject jsonObject = new JsonParser().parse(builder.toString()).getAsJsonObject();
			String errcode = jsonObject.get("errcode").getAsString();
			String errmsg = jsonObject.get("errmsg").getAsString();
			ticket = jsonObject.get("ticket").getAsString();
			expires_in = jsonObject.get("expires_in").getAsInt();
			//生成签名
			String signature = sha1(ticket,nonceStr,time+"",baseUrl);
			JsApiTicket jsApiTicket = new JsApiTicket(baseUrl,ticket,time+"", nonceStr, signature, expires_in);
			jsTicket=jsApiTicket;
			session.setAttribute("jsTicket", jsTicket);
			return jsApiTicket;
		}else {
			return jsTicket;
		}
		
	}
	
	
	//进行sha1加密
	private static String sha1(String ticket,String noncestr,String timestamp,String url){
		String str="jsapi_ticket=" + ticket + "&noncestr=" + noncestr
				+ "&timestamp=" + timestamp + "&url=" + url;
		MessageDigest md ;
		try {
			md = MessageDigest.getInstance("SHA-1");
		} catch (NoSuchAlgorithmException e) {
			System.out.println("SHA1加密失败，");
			return null;
		}
		byte[] digestByteArray = md.digest(str.getBytes());
		//把最终的结果转成16进制字符串
		StringBuffer digestStr = new StringBuffer();
		String temp="";
		for (byte b : digestByteArray) {
			temp = Integer.toHexString(b&0xFF);
			if (temp.length()==2) {
				digestStr.append(temp);
			}else {
				digestStr.append('0').append(temp);
			}
		}
		return digestStr.toString();
	}
}
